package com.threeti.mecool.common.resource.core;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.Validate;
import org.springframework.core.io.Resource;

import com.threeti.mecool.common.resource.Content;
import com.threeti.mecool.common.resource.SearchableContent;
import com.threeti.mecool.common.resource.filter.ContentFilter;
import com.threeti.mecool.common.resource.filter.ContentFilterStrategy;
import com.threeti.mecool.common.resource.filter.ContentFilterStrategyManager;

/** based on UrlResource */
public class DefaultContent implements SearchableContent {

	private Resource fsRes;
	
	private ContentFilterStrategy filterStrategy = ContentFilterStrategyManager.defaultStrategy();

	public DefaultContent(Resource fsRes) {
		Validate.notNull(fsRes, "文件系统资源不能为空");
		this.fsRes = fsRes;
	}

	@Override
	public boolean exists() {
		return fsRes.exists();
	}

	@Override
	public boolean isReadable() {
		return fsRes.isReadable();
	}

	@Override
	public boolean isOpen() {
		return fsRes.isOpen();
	}

	@Override
	public URL getURL() throws IOException {
		return fsRes.getURL();
	}

	@Override
	public URI getURI() throws IOException {
		return fsRes.getURI();
	}

	@Override
	public File getFile() throws IOException {
		return fsRes.getFile();
	}

	@Override
	public long contentLength() throws IOException {
		if (fsRes.getFile().isDirectory()) {
			return FileUtils.sizeOfDirectory(fsRes.getFile());
		}
		return fsRes.contentLength();
	}

	@Override
	public long lastModified() throws IOException {
		return fsRes.lastModified();
	}

	@Override
	public String getFilename() {
		return fsRes.getFilename();
	}

	@Override
	public String getDescription() {
		return fsRes.getDescription();
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return fsRes.getInputStream();
	}

	public byte[] getBytes() throws IOException {
		return IOUtils.toByteArray(getInputStream());
	}
	
	public List<Content> list(ContentFilter filter) throws IOException {//TODO jay:more UT
		Validate.notNull(filterStrategy, "内容资源的筛选策略不能为空");
		return filterStrategy.queryForContents(this, filter);
	}
	
	public SearchableContent applyFilterStrategy(ContentFilterStrategy filterStrategy) {
		this.filterStrategy = filterStrategy;
		return this;
	}

}
